package com.develop.data.loan.jpa.attribute.converter;

import org.javamoney.moneta.Money;

import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.*;

@Converter
public class LoanMoneyAmountAttributeConverter implements AttributeConverter<MonetaryAmount, String> {

    private static final MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.ROOT);

    @Override
    public String convertToDatabaseColumn(MonetaryAmount moneyAmount) {
        return Optional.ofNullable(moneyAmount)
                .map(format::format)
                .orElse(null);
    }

    @Override
    public MonetaryAmount convertToEntityAttribute(String item) {
        return Optional.ofNullable(item)
                .map(format::parse)
                .orElse(null);
    }
}

